import { ServiceException } from '../common/excpetion';
import { Guid } from './../common/utils/guid';
export class VerifyCodeManager {
    static Current: VerifyCodeManager = new VerifyCodeManager();
    private codeList = new Map<string, { code: number; ts: number; }>();
    GetVerifyCode() {
        let r = {
            id: Guid.GetGuid(),
            code: parseInt((Math.random() * 9000 + 1000).toString())
        }
        this.codeList.set(r.id, {
            code: r.code,
            ts: Date.now()
        });

        return r;
    }

    Verify(key: string, code: number) {
        this.clearTimeoutCode();
        let item = this.codeList.get(key);
        if (!item) {
            throw new ServiceException('验证码过期！');
        }
        if (item.code != code) {
            throw new ServiceException('验证码错误！');
        }

        this.codeList.delete(key);
    }

    clearTimeoutCode() {
        this.codeList.forEach((value, key) => {
            if ((Date.now() - value.ts) > 120 * 1000) {
                // 超时5分钟
                this.codeList.delete(key);
            }
        })
    }
}